addEvent("onload", init);
addEvent("onresize", checkOrientation);

var screenmode = 0;

function init(){
    try {
        var myStyleTweaks = new StyleTweaker();
        myStyleTweaks.add("Series60/5.0", "styles/tweaks/S605th.css");
        myStyleTweaks.add("Series60/3.2", "styles/tweaks/S603rdFP2.css");
        myStyleTweaks.tweak();
        
		initService();
        listContacts();
    } 
    catch (e) {
        alert(e.toString());
    }
}

function checkOrientation(){
    try {
        var width = parseInt(screen.width);
        var height = parseInt(screen.height);
        
        //var landscapeTweaker = new StyleTweaker();
        // Landscape tweaks for template styles not available in templates?
        //landscapeTweaker.add("Series60/5.0", "../resources/styles/tweaks/S605thLandscape.css");
        
        if (width > height) {
        
            // if already in landscape mode, return
            if (screenmode == 1) 
                return;
            screenmode = 1;
            // landscapeTweaker.tweak();
        }
        else {
            // if already in portrait mode, return
            if (screenmode == 0) 
                return;
            screenmode = 0;
            //        landscapeTweaker.untweak();
        }
    } 
    catch (e) {
        alert(e.toString());
    }
}

/*
 * Shows the content of selected tab.
 * tab - tab to be shown
 */
function show(tab, tid){
    document.getElementById("nameGroup").style.display = "none";
	document.getElementById("a1").className = "";
    document.getElementById("telGroup").style.display = "none";
	document.getElementById("a2").className = "";
    document.getElementById("addressGroup").style.display = "none";
	document.getElementById("a3").className = "";
    document.getElementById("companyGroup").style.display = "none";
	document.getElementById("a4").className = "";
    
    document.getElementById(tab).style.display = "block";
	document.getElementById(tid).className = "selectedTab";
}

/*
 * Shows new contact form
 */
function newContact(){
    document.contact.contactID.value = "";
    
    cleanForm();
    document.getElementById("header2").innerHTML = "New Contact";
    document.getElementById("contactListContainer").style.display = "none";
	show("nameGroup","a1");
    document.getElementById("singleContactContainer").style.display = "block";
}

/*
 * Shows selected contact in contact form
 * id - unique identifier of contact
 * Contact information is retrieved by getContact(id) function defined in platformservices_20_specific.js
 */
function openContact(id){
    document.contact.contactID.value = id;
    var contactEntry = getContact(id);
    
    if (contactEntry != null) {
        preFillContactForm(contactEntry);
        var header = (contactEntry.name == null) ? "(unnamed)" : getValue(contactEntry.name.last) + " " + getValue(contactEntry.name.first);
        document.getElementById("header2").innerHTML = header;
        document.getElementById("contactListContainer").style.display = "none";
		show("nameGroup","a1");
        document.getElementById("singleContactContainer").style.display = "block";
    }
    else 
        alert("Error retrieving contact info.");
}

/*
 * Shows list of contacts
 */
function showContactList(){
    document.getElementById("contactListContainer").style.display = "block";
    document.getElementById("singleContactContainer").style.display = "none";
}

/*
 * Sets all contact checkboxes to specified status
 * checked - status to be set: true or false
 */
function chALL(checked){
	var items = document.f1.ch;
	if(items==null) return;
	if(items.length){
		for (var i = 0; i < items.length; i++) {
			items[i].checked = checked;
		}
	}else
		items.checked = checked;
}

/*
 * Sets 'all' checkbox to 'checked' status if all contact checkboxes are checked 
 */
function checkMain(){
	var items = document.f1.ch;
	if(items==null) return;
	var checked = true;
	if (items.length) {
		for (var i = 0; i < items.length; i++) {
			checked = checked && items[i].checked;
		}
	}else
		checked = items.checked;
	document.f1.chAll.checked = checked;
}


/*
 * Deletes all selected contacts and refreshes contact list
 * deleteContact(id) is defined in platformservices_20_specific.js
 */
function deleteContacts(){
    if (!confirm('Delete selected contact(s)?')) 
        return;
    
    var contacts = document.f1.ch;
	if(contacts==null) return;
    if (contacts.length) {
		for (var i = 0; i < contacts.length; i++) {
			if (contacts[i].checked) {
				deleteContact(contacts[i].value);
			}
		}
	}else
		deleteContact(contacts.value);
		
    listContacts();
}

/*
 * Builds one row for contact list HTML table based on contact entry data.
 */
function showContact(entry){
    var txt = "<tr>";
    try {
        txt += "<td width='5'><input type='checkbox' onclick='checkMain()' name='ch' value='" + entry.id + "'/></td>";
        if (entry.name != null) 
            txt += "<td><a href=\"#\" onClick=\"openContact('" + entry.id + "');\">" + (entry.name.first == null ? "" : (entry.name.first + "&nbsp;")) + (entry.name.last == null ? "" : entry.name.last) + "</a></td>";
        else 
            txt += "<td><a href=\"#\" onClick=\"openContact('" + entry.id + "');\">(unnamed)</a></td>";
        if (entry.tel != null) 
            txt += "<td>" + (entry.tel.mobile == null ? "" : entry.tel.mobile) + "</td>";
        else 
            txt += "<td></td>";
    } 
    catch (e) {
        alert("showContact: " + e);
    }
    txt += "</tr>";
    return txt;
    
}

/*
 * Saves contact form data.
 * if contact id value is found existing contact is updated, new contact is created otherwise.
 * addContact() and updateContact(id) are defined in platformservices_20_specific.js
 */
function saveContact(){
    var id = document.contact.contactID.value;
    if (id == "") 
        addContact();
    else 
        updateContact(id);
    
    document.getElementById("contactFilter").value = "";
    listContacts();
    showContactList();
}

/*
 * Creates new contact entry based on contact form data.
 * Contact schema:
 * {
 *  name:{
 *        last:'last name',
 *        first: 'first name',
 *        middle: 'middle name',
 *        prefix: 'name prefix',
 *        suffix: 'name suffix'
 *       },
 *  tel:{
 *       land: 'landline number',
 *       mobile: 'mobile number',
 *       video: 'video number',
 *       fax: 'fax number',
 *       voip: 'voip number',
 *       home:{
 *             land: 'landline number',
 *             mobile: 'mobile number',
 *             video: 'video number',
 *             fax: 'fax number',
 *             voip: 'voip number'
 *            },
 *       work:{
 *             land: 'landline number',
 *             mobile: 'mobile number',
 *             video: 'video number',
 *             fax: 'fax number',
 *             voip: 'voip number'
 *            },
 *      },
 *  address: {
 *            street: 'street address',
 *            local:  'locality (e.g. city)',
 *            region: 'region (e.g. state)',
 *            code: 'postal code',
 *            country: 'country',
 *            email: 'email address',
 *            url: 'web address',
 *            home: {
 *                   street: 'street address',
 *                   local:  'locality (e.g. city)',
 *                   region: 'region (e.g. state)',
 *                   code: 'postal code',
 *                   country: 'country',
 *                   email: 'email address',
 *                   url: 'web address'
 *                  },
 *            work: {
 *                   street: 'street address',
 *                   local:  'locality (e.g. city)',
 *                   region: 'region (e.g. state)',
 *                   code: 'postal code',
 *                   country: 'country',
 *                   email: 'email address',
 *                   url: 'web address'
 *                  }
 *           },
 *   company: {
 *             name: 'company name',
 *             title: 'job title'
 *            },
 *   id: {} // Applications must treat the ID object as opaque data. 
 *    
 * }
 */
function prepareContactEntry(){
    var form = document.contact;
    var contactEntry = new Object();
    var contactName = new Object();
    var contactTel = new Object();
    var contactAddress = new Object();
    var contactCompany = new Object();
    
    contactEntry.name = contactName;
    contactEntry.tel = contactTel;
    contactEntry.address = contactAddress;
    contactEntry.company = contactCompany;
    
    contactName.last = form.lname.value;
    contactName.first = form.fname.value;
    contactName.middle = form.mname.value;
    contactName.prefix = form.pref.value;
    contactName.suffix = form.suf.value;
    
    contactTel.land = form.land.value;
    contactTel.mobile = form.mobile.value;
    contactTel.video = form.video.value;
    contactTel.fax = form.fax.value;
    //contactTel.voip = form.voip.value;//Not Supported on Nokia 5800 and 323 Devices
    
    contactAddress.street = form.street.value;
    contactAddress.local = form.city.value;
    contactAddress.region = form.region.value;
    contactAddress.code = form.pcode.value;
    contactAddress.country = form.country.value;
    contactAddress.email = form.email.value;
    contactAddress.url = form.url.value;
    
    contactCompany.name = form.cname.value;
    contactCompany.title = form.jtitle.value;
    
    return contactEntry;
}

/*
 * Fills contact form based on specified contactEntry object
 * Contact schema: see prepareContactEntry
 */
function preFillContactForm(contactEntry){
    var form = document.contact;
    cleanForm();
    if (contactEntry.name != null) {
        form.lname.value = getValue(contactEntry.name.last);
        form.fname.value = getValue(contactEntry.name.first);
        form.mname.value = getValue(contactEntry.name.middle);
        form.pref.value = getValue(contactEntry.name.prefix);
        form.suf.value = getValue(contactEntry.name.suffix);
    }
    if (contactEntry.tel != null) {
        form.land.value = getValue(contactEntry.tel.land);
        form.mobile.value = getValue(contactEntry.tel.mobile);
        form.video.value = getValue(contactEntry.tel.video);
        form.fax.value = getValue(contactEntry.tel.fax);
        form.voip.value = getValue(contactEntry.tel.voip);
    }
    if (contactEntry.address != null) {
        form.street.value = getValue(contactEntry.address.street);
        form.city.value = getValue(contactEntry.address.local);
        form.region.value = getValue(contactEntry.address.region);
        form.pcode.value = getValue(contactEntry.address.code);
        form.country.value = getValue(contactEntry.address.country);
        form.email.value = getValue(contactEntry.address.email);
        form.url.value = getValue(contactEntry.address.url);
    }
    if (contactEntry.company != null) {
        form.cname.value = getValue(contactEntry.company.name);
        form.jtitle.value = getValue(contactEntry.company.title);
    }
}

/* 
 * Returns value if it is not null, otherwise empty string is returned
 */
function getValue(v){
    if (v == null) 
        return "";
    return v;
}

/*
 * Empties all contact form member elements
 */
function cleanForm(){
    document.contact.reset();
}